import {openStdin} from 'process'
import { operation} from 'retry'
import { KeyboardEvent } from './event'
import { TextModel , SelectionModel} from './models';
import {InsertTextOperation, RemoveTextOperations, SetSelectionOperation} from './operations'
import { RenderView } from './view'

class Editor {
  textModel_: TextModel = new TextModel;
  selectionModel_!: SelectionModel;
  view_!: RenderView;
  eventHandler!: KeyboardEvent;
  container: HTMLElement ;

  constructor(container: HTMLElement  ) {
    this.container = container
  }
  init(){
    this.textModel_ = new TextModel()
    this.selectionModel_ = new SelectionModel(this.textModel_)
    this.view_ = new RenderView(this.textModel_, this.selectionModel_, this.container)
    this.eventHandler = new KeyboardEvent(this, this.container, this.view_)
    this.eventHandler.addListeners()
  }
  // 获取文本模型
  getTextModel(){
    return this.textModel_
  }
  // 获取当前的选区模型
  getSelectionModel(){
    return this.selectionModel_
  }
  apply(operation:any){
    operation.apply(this)
  }
  // 在光标位置增加数据
  insertTextAtCursor(text: string | any[]){
    const selection = this.selectionModel_.getSelection()
    let startIndex = selection.anchor
    let cursorIndex
    // 如果有选区 会将选区先删除 再进行添加替换
    if(!this.selectionModel_.isOverlap()){
      const removeTextOperations = new RemoveTextOperations(selection.anchor, selection.focus)
      this.apply(removeTextOperations)
      if(this.selectionModel_.isBackward()){
        startIndex = selection.focus
      }
    }
    cursorIndex = startIndex + text.length
    const insertTextOperation = new InsertTextOperation(text, startIndex)
    this.apply(insertTextOperation)
    this.setSelection(cursorIndex, cursorIndex)
  }
  // 在光标位置删除数据
  deleteTextAtCursor() {
    const selection = this.selectionModel_.getSelection()
    let startIndex = selection.anchor
    let endIndex = selection.focus
    if (!this.selectionModel_.isOverlap()) {
      this.apply(new RemoveTextOperations(startIndex, startIndex))
      // 从后向前选 就把光标更新前面
      if (this.selectionModel_.isBackward()) {
        startIndex = selection.focus
      }
    } else if(startIndex >0) {
      // 如果没有选则数据 则光标位置往当前位置 前面移动一位
      this.apply(new RemoveTextOperations(startIndex -1, endIndex))
      startIndex--
    }
    // 最后统一设置选区
    this.setSelection(startIndex, startIndex)
  }
  setSelection(anchor: any, focus: any){
    const selectionOperation = new SetSelectionOperation({anchor, focus})
    this.apply(selectionOperation)
  }

}

export default Editor